/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.clebersantos.util;

import br.com.clebersantos.Main;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.TooManyListenersException;

/**
 *
 * @author Cleber Santos - santos.cleber@gmail.com 11 9.8140.5393
 */
public class ReadListener implements SerialPortEventListener {
    
    private BufferedReader input;
    private InputStream inStream;
    private SerialPort serialPort;
    private byte[] buffer = new byte[1024];
    private int availableBytes;

    @Override
    public void serialEvent(SerialPortEvent spe) {       

        if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {             
            
            int len = -1;
            
            try {
                inStream = serialPort.getInputStream();            
                availableBytes = inStream.available();
                if(availableBytes > 0){
                    inStream.read(buffer, 0, availableBytes);
                    System.out.println(new String(buffer, 0, availableBytes));
                    Thread t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            Main.getInstance().escreverArea(new String(buffer, 0, availableBytes));
                        }
                    });
                    t.run();
                }
            } catch (Exception e) {
                System.err.println("Erro ReadListener: " + e);
            }
        }

    }

    public void rodar(SerialPort port) throws IOException, TooManyListenersException {

        this.serialPort = port;
        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

        //adiciona listeners para saber quando chegou um novo dado
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException ie) {
                    System.err.println("erro: " + ie);
                }
            }
        };
        t.start();
        System.out.println("Started Reader");
    }

}
